import { defineStore } from 'pinia'
import { reactive} from 'vue'
import {getContactsInfo,getContactMessage} from "@/api/disk/user"
import {userStore} from '@/stores/disk/user';
function initState(){
  return {
    showAddContactsDialog:false,//显示添加联系人对话框
    showAll:false,//显示输入框和消息列表
    contacts: [],//联系人列表
    messages: [],//聊天消息
    socket: null,//socket连接
    currentContact: null,//当前聊天对象
    activeContactId: null,//当前聊天对象id
    showFileSelect: false,//显示文件选择框
  }
}


export const chatStore = defineStore('chat', (a) => {
      const state=reactive(initState())
      
      function updateShowAddContactsDialog(val){
        state.showAddContactsDialog=val
      }

      //获取联系人信息
      async function getContacts(){
        const data={
          userSelf:localStorage.getItem('userId'),
          status:0
        }
        const res = await getContactsInfo(data)
        state.contacts = res.rows
      }
      //获取联系人聊天消息
      async function getMessages(){
        const userStor=userStore();
        const data={
          userSelf: parseInt(localStorage.getItem('userId')),
          userOther: state.currentContact.userOther
        }
        const res = await getContactMessage(data)
        const userId= parseInt(localStorage.getItem('userId'))
        const mess = res.data.map(msg => ({
          id: msg.id,
          contactId: state.currentContact.id,
          avatar: msg.senderId === userId ? userStor.state.userInfo.avatar : state.currentContact.avatar,
          sender: msg.senderId === userId ? 'me' : 'other',
          text: msg.content,
          time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
        }));
        state.messages = mess
      }
      //更新当前联系人ID
      function updateActiveContactId(val){
        state.activeContactId=val
      }
      //更新当前联系人信息
      function updateContactInfo(val){
        state.contacts=val
      }
      //添加聊天消息
      function addMessage(payload) {
        state.messages.push(payload)
        // 更新对应联系人的最后消息
        state.contacts = state.contacts.map(contact => {
          if (contact.id === payload.contactId) {
            contact.lastMessage = payload.text;
            return contact;
          }
          return contact;
        });
      }
      //显示输入框和消息列表
      function showAll(){
        state.showAll=true
      }
      //更新userOther
      function updateCurrentContact(val){
        state.currentContact=val
      }
      //显示文件选择框
      function showFileSelectAll(val){
        state.showFileSelect=val
      }
      //保存socket
      function connectSocket(val){
        state.socket=val
      }
      return {
        state,
        updateShowAddContactsDialog,
        getContacts,
        getMessages,
        addMessage,
        showAll,
        updateCurrentContact,
        showFileSelectAll,
        connectSocket,
        updateActiveContactId,
        updateContactInfo
      }
})